<?php
namespace app\common\model;

use app\common\logic\UserExtend;
use app\common\service\App;
use app\common\service\SingleService;
use think\Db;
use think\Model;


class Users extends Model
{
    protected $dateFormat = 'Y-m-d H:i';

    public function profile()
    {
        return $this->hasOne('users', 'user_id', 'proxy_id')->field('nick_name');
    }
    public function skill()
    {
        return $this->hasOne(Skill::class,'skill_id','skill_id');
    }

    public function opinion()
    {
        return $this->hasOne(Opinion::class,'user_id','user_id');
    }

    public function extend()
    {
        return $this->hasOne(UserExtend::class,'user_id','user_id');
    }

    public function getDetail($where = [])
    {
        $join = [
            ['user_extend e','e.user_id = a.user_id','left']
        ];
        $field = 'a.is_real,a.header_img,a.nick_name,a.sex,a.uuid,a.grade,a.ID,a.phone,e.wx_name,e.wb_name,e.qq_name,e.invite,e.filter,e.dispatch,e.filter,e.hall,e.LabourUnion';

        return $this->alias('a')
            ->join($join)
            ->where($where)
            ->field($field)
            ->find();
    }

    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 编辑个人资料页面返显
     */
    public function getInfo($user_id = 0)
    {
        $where['a.user_id'] = $user_id;
        $map['user_id'] = $user_id;
        $data = $this->alias('a')->where($where)
            ->join('user_extend e','e.user_id = a.user_id','left')
            ->field('a.is_real,a.user_id,a.header_img,a.nick_name,a.sex,a.tag,a.sign,a.birthday,a.job,a.uuid,a.grade,a.phone,e.level,e.noble_id,e.noble_time,e.is_year,e.member_time')
            ->find();
        $map['type']   = 1;
        $map['status'] = 1;
        $imgs  = Db::name('user_img')->where($map)->field('img_id,img')->select();

        foreach ($imgs as $k => $v){
            $imgs[$k]['original_img'] = $v['img'];
//            $imgs[$k]['img'] = getThumb($v['img'],300);
            //2020-1-2  去除缩略图
            $imgs[$k]['img'] = $v['img'];
        }

        if ($data['member_time'] > time()){

            if ($data['is_year'] == 1){
                $data['is_member'] = 2;
            }else{
                $data['is_member'] = 1;
            }
        }else{
            $data['is_member'] = 0;
        }

        $data['imgs'] = $imgs;

        $data['img_max'] = Db::name('extend')->where('id',1)->cache(60)->value('img_max');
        $data['noble_id'] = \app\api\controller\Base::checkNoble($data);
        $data['user_id'] = hashid($data['user_id']);
        $data['original_img'] = $data['header_img'];
        $data['header_img'] = getThumb($data['header_img'],300);

        return $data;
    }




    /**
     * 后台获取用户列表
     */
    public function userList($where = [])
    {
        return $this->alias('a')
            ->join('user_extend e','e.user_id = a.user_id','left')
            ->where($where)
            ->field('a.*,e.*')
            ->order('a.user_id desc')
            ->paginate('', false, ['query' => request()->param()]);
    }


    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 家族申请列表获取用户  房间管理获取用户
     */
    public function getItems($map = [],$room_id = false)
    {
        $join = [
            ['user_extend e','e.user_id = a.user_id','left']
        ];

        $field = 'a.user_id,a.header_img,a.sex,a.nick_name,a.tag,e.noble_id,e.noble_time,e.level,a.birthday';

        $rows =  $this->alias('a')
            ->where($map)
            ->join($join)
            ->field($field)
            ->order('e.online_status desc')
            ->cache(2)
            ->paginate()->each(function ($item)use ($room_id){
                $item['noble_id'] = \app\api\controller\Base::checkNoble($item);
                $item['age'] = getAge($item['birthday']);
                if (is_numeric($room_id)){
                    $item['power'] = getPowerCode($item['user_id'],$room_id);
                }
                $item['user_id'] = hashid($item['user_id']);
            });
        return ['thisPage'=>$rows->currentPage(),'hasNext'=>$rows->hasMore(),'data'=>$rows->items()];
    }

    public function getNoble($map = [])
    {
        $join = [
            ['user_extend e','e.user_id = a.user_id','left']
        ];

        $field = 'a.user_id,a.header_img,a.nick_name,a.sign,e.noble_id,e.noble_time,e.online_time,e.online_status';

        $rows =  $this->alias('a')
            ->where($map)
            ->join($join)
            ->field($field)
            ->order(['e.noble_id'=>'desc','noble_time'=>'desc'])
            ->cache(15)
            ->paginate()->each(function ($item){
                $item['noble_id'] = \app\api\controller\Base::checkNoble($item);

                if ($item['online_status']){
                    $item['status'] = '当前在线';
                }else{
                    $item['status'] = formatTime($item['online_time']);
                }

                $item['user_id'] = hashid($item['user_id']);
            });
        return ['thisPage'=>$rows->currentPage(),'hasNext'=>$rows->hasMore(),'data'=>$rows->items()];
    }



    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 广场获取
     */
    public function rows($map = [],$user_id = 0,$order = '',$skill_id = false,$page = 16,$changeTime = false)
    {

        $join = [
            ['user_extend e','e.user_id = a.user_id','left'],
            ['room r','r.room_id = e.room_id','left']
        ];
        //修改大厅必有技能  因此注释
        if ($skill_id){
            $join[] = ['skill_apply s','s.user_id = a.user_id','right'];
        }

//        if ($user_id != 0){ //存在用户id   排除自己
//            $map['a.user_id'] = ['neq',$user_id];
//        }

//        $field = 'a.birthday,a.user_id,a.header_img,a.sex,a.nick_name,a.sign,e.online_time,e.online_status,e.room_id,e.noble_id,e.noble_time,e.place,e.level,r.is_lock,r.password';
        $field = 'e.city,a.is_real,a.custom_sign,a.birthday,a.user_id,a.header_img,a.sex,a.nick_name,a.sign,e.online_time,e.online_status,e.room_id,e.noble_id,e.noble_time,e.place,e.level,r.is_lock,r.password,e.is_year,e.member_time';

        $rows = $this->alias('a')
            ->group('a.user_id')
            ->where($map)
            ->join($join)
            ->field($field)
            ->orderRaw($order)
//            ->order($order)
            ->cache(15)

            ->paginate($page);


        $items   = $rows->items();
//        $page = input('page')??1;
//        if ($page == 1){
//            //查找为第一页时   第一个用户显示自己
//            $self =  $this->alias('a')->where('a.user_id',$user_id)->join($join)
//                ->field($field)
//                ->cache(15)
//                ->find();
//
//            if ($self){
//                array_unshift($items,$self);
//            }
//        }
        foreach ($items as $k => $item){
            if (empty($item['sign'])){
                $items[$k]['sign'] = '你不主动，我们之间怎么会有故事～';
            }

            if ($item['member_time'] > time()){

                if ($item['is_year'] == 1){
                    $items[$k]['is_member'] = 2;
                }else{
                    $items[$k]['is_member'] = 1;
                }
            }else{
                $items[$k]['is_member'] = 0;
            }

            $items[$k]['header_img']   = getThumb($item['header_img'],App::getExplain('square_px'));

            if (is_numeric($skill_id)){
                //ios 审核中不能筛选技能
                if (get_device_type() == 'ios' && App::getExplain('ios_check') === 'true'){
                    $array = array_merge(explode(',',App::getExplain('ios_check_cate_1')) ,explode(',',App::getExplain('ios_check_cate_2')));
                    if (in_array($skill_id,$array)){
                        $where['s.skill_id'] = $skill_id;
                    }else{
                        $where['s.skill_id'] = ['in',App::getExplain('ios_check_cate_1').','.App::getExplain('ios_check_cate_2')];
                    }
                }else{
                    $where['s.skill_id'] = $skill_id;
                }

            }else{
                if (get_device_type() == 'ios' && App::getExplain('ios_check') === 'true'){
                    $where['s.skill_id'] = ['in',App::getExplain('ios_check_cate_1').','.App::getExplain('ios_check_cate_2')];
                }
            }
            $where['s.user_id'] = $item['user_id'];
            $where['s.is_use']  = 1;
            $where['s.status']  = 1;



            $skill = Db::name('skill_apply')
                ->alias('s')
                ->join('skill sk','s.skill_id = sk.skill_id','left')
                ->where($where)
                ->field('sk.type,s.apply_id,sk.skill_name,s.num,s.is_use,s.status,s.update_time,s.skill_id,s.explain,s.voice')
                ->order('sk.sort desc')
                ->cache(2)
                ->find();

            $items[$k]['apply_id']   = $skill['apply_id']??0;
            $items[$k]['skill_name'] = $skill['skill_name']??'';
            $items[$k]['skill_type'] = $skill['type']??1;
            $items[$k]['num']        = $skill['num'] >= 5?$skill['num']:5;
            $items[$k]['is_use']     = $skill['is_use']??0;

            if ($item['custom_sign']){
                $items[$k]['explain']    = $item['custom_sign'];
            }else{
                $items[$k]['explain']    = $skill['explain'];
            }

            $items[$k]['voice']     = $skill['voice']??'';
            if ($items[$k]['apply_id'] != 0){
                $map1['user_id']  = $item['user_id'];
                $map1['skill_id'] = $skill['skill_id'];
                $map1['status']   = 1;
                $items[$k]['mini_price'] = Db::name('skill_form_user')->where($map1)->order('mini_price')->cache(2)->value('mini_price')??0;
            }else{
                $items[$k]['mini_price'] = 0;
            }


            if ($item['online_status']){
                $items[$k]['status'] = '当前在线';
            }else{
                if (isInt($item['room_id'])){ //如果用户为离线状态  且房间id不为0  退出房间
                    $item['room_id'] = 0;
                    Db::name('user_extend')->where('user_id',$item['user_id'])->update(['room_id'=>0]);
                }
                $time = formatTime($item['online_time']);

                if (empty($time) && $changeTime){
                    $items[$k]['status'] = '当前在线';
                }else{
                    $items[$k]['status'] = $time;
                }

            }


            if ($item['is_lock'] === null){
                $item['is_lock'] = 0;
            }
            if ($item['password'] === null){
                $item['password'] = '';
            }

            $items[$k]['noble_id'] = \app\api\controller\Base::checkNoble($item);
            $items[$k]['noble_name'] = getNobleName($item['noble_id']);

            if (input('page',1) <= 5 && App::getUserId())
            {
                if (!empty($item['user_id'])){
                    //已登录第一页记录下已筛选用户
                    SingleService::add(SingleService::SquareUser, "{$item['user_id']}");
                }

            }

            $items[$k]['user_id'] = hashid($item['user_id']);

            if (isInt($item['room_id'])){
                $items[$k]['power'] = getPowerCode($user_id,$item['room_id']);
            }else{
                $items[$k]['power'] = 4;
            }

            unset($items[$k]['online_status']);
            unset($items[$k]['online_time']);
            unset($items[$k]['noble_time']);
            unset($items[$k]['is_use']);
            unset($items[$k]['birthday']);

//            unset($items[$k]['mini_price']);
//            unset($items[$k]['place']);
        }

        return ['thisPage'=>$rows->currentPage(),'hasNext'=>$rows->hasMore(),'data'=>$items];
    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     */
    public function search($map = [],$user_id = 0,$distance = false,$userExtra = [])
    {

        if ($distance){

            $max  = Db::name('extend')->where('id',1)->cache(60)->value('distance');

            $join = [
                ['user_extend e','e.user_id = a.user_id','left'],
            ];

            $log = $userExtra['log'];
            $lat = $userExtra['lat'];
            if (!$log){
                api_return(0,'无定位信息');
            }
            $field = "e.place,(st_distance (point (e.log,e.lat),point($log,$lat) ) / 0.0111) AS distance,a.user_id,a.uuid,a.nick_name,a.header_img";
            $items =  $this->alias('a')->where($map)->join($join)
                ->field($field)
                ->order('distance')
                ->having("distance < $max")
                ->cache(15)
                ->select();
            $thisPage = 1;
            $hasNext  = false;

        }else{

            $rows = $this->alias('a')
                ->where($map)
                ->field('a.user_id,a.uuid,a.nick_name,a.header_img')
                ->group('a.user_id')
                ->paginate();
            $thisPage = $rows->currentPage();
            $hasNext = $rows->hasMore();
            $items = $rows->items();

        }

        $where['user_id'] = $user_id;
        $where['status']  = 1;

        foreach ($items as $k => $v){

            $where['follow_user']   = $v['user_id'];
            $items[$k]['is_follow'] = Db::name('user_follow')->where($where)->value('follow_id')?1:0;
            $items[$k]['user_id']   = hashid($v['user_id']);

        }

        return ['thisPage'=>$thisPage,'hasNext'=>$hasNext,'data'=>$items];
    }


    public function getCity($map = [],$max = 60,$order,$userExtra = [])
    {

        $join = [
            ['user_extend e','e.user_id = u.user_id','left'],
        ];

        $log = $userExtra['log'];
        $lat = $userExtra['lat'];
        if (!$log){
            api_return(0,'无定位信息');
        }
        $field = "u.is_real,e.is_year,e.member_time,e.place,(st_distance (point (e.log,e.lat),point($log,$lat) ) / 0.0111) AS distance,u.user_id,u.uuid,u.nick_name,u.header_img,u.sex,u.sign,e.online_time,e.online_status,e.room_id,e.noble_id,e.noble_time,e.level";

        $page = input('page')??1;
        $items =  $this->alias('u')
            ->where($map)
            ->join($join)
            ->field($field)
            ->order($order)
            ->having("distance < $max")
            ->cache(30)
            ->page($page,20)
            ->select();
        $thisPage = 1;
        $hasNext  = false;

        foreach ($items as $k => $v){

            if ($v['member_time'] > time()){

                if ($v['is_year'] == 1){
                    $items[$k]['is_member'] = 2;
                }else{
                    $items[$k]['is_member'] = 1;
                }
            }else{
                $items[$k]['is_member'] = 0;
            }

            $items[$k]['header_img']   = getThumb($v['header_img'],App::getExplain('square_px'));
            if ($v['online_status']){
                $items[$k]['status'] = '当前在线';
            }else{
                $items[$k]['status'] = formatTime($v['online_time'],2);
            }
            $items[$k]['noble_id'] = \app\api\controller\Base::checkNoble($v);
            $items[$k]['noble_name'] = getNobleName($v['noble_id']);
            if ($v['room_id']){
                $skill = false;
//                $rows[$k]['skill'] = $_empty;
                $items[$k]['is_lock'] = \app\api\controller\Base::roomInfo($v['room_id'],'is_lock');
                $items[$k]['password'] = \app\api\controller\Base::roomInfo($v['room_id'],'password');
                $items[$k]['power']   = getPowerCode($v['user_id'],$v['room_id']);
            }else{
                $items[$k]['is_lock']  = 0;
                $items[$k]['password'] = '';
                $items[$k]['power']    = 4;

                //不在房间内查询是否有技能
                $where['a.user_id'] = $v['user_id'];
                $where['a.status']  = 1;
                $where['f.user_id'] = $v['user_id'];
                $where['a.is_use']  = 1;
                if (get_device_type() == 'ios' && App::getExplain('ios_check') === 'true'){
                    $where['a.skill_id'] = ['in',App::getExplain('ios_check_cate_1').','.App::getExplain('ios_check_cate_2')];
                }
                $skill = Db::name('skill_apply')
                    ->alias('a')
                    ->where($where)
                    ->join([
                        ['skill s','s.skill_id = a.skill_id','left'],
                        ['skill_form_user f','f.skill_id = a.skill_id','left'],
                    ])
                    ->order('s.sort desc,f.mini_price')
                    ->field('a.apply_id,s.skill_name,a.explain,a.num,f.mini_price,a.voice')
                    ->find();
            }

            $_empty = [
                'apply_id' => 0,
                'skill_name' => '',
                'explain' => '',
                'voice' => ''
            ];
            if ($skill){
                $items[$k]['num'] = $skill['num'] >5 ?$skill['num']:5;
                $items[$k]['mini_price'] = $skill['mini_price'];
                unset($skill['num']);
                unset($skill['mini_price']);
                $items[$k]['skill'] = $skill;
            }else{
                $items[$k]['num'] = 5;
                $items[$k]['mini_price'] = 0;
                $items[$k]['skill'] = $_empty;
            }
            $items[$k]['user_id']   = hashid($v['user_id']);

        }

        return ['thisPage'=>$page,'hasNext'=>true,'data'=>$items];
    }


    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 用户信息列表  上麦请求获取
     */
    public function _list(array $map = []): array
    {

        $join = [
            ['user_extend e','e.user_id = a.user_id','left'],
        ];

        $field = "a.user_id,a.nick_name,a.header_img,e.noble_id,e.level";

        $rows = $items =  $this->alias('a')->where($map)->join($join)
            ->field($field)
            ->cache(2)
            ->select();
        foreach ($rows as $k => $v){
            $rows[$k]['user_id'] = hashid($v['user_id']);
        }

        return $rows;

    }


}